//
// IwTools.cs
//
// Copyright (C) 2008 Lukas Lipka <lukaslipka@gmail.com>
//

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;

using Dashboard.Engine.Fidelity;

namespace IwTools {

	public class IwList : IScanner {

		public IEnumerable<Network> Scan ()
		{
			ProcessStartInfo psi = new ProcessStartInfo ("iwlist", "eth1 scan");
			psi.RedirectStandardOutput = true;
			psi.RedirectStandardError = true;
			psi.UseShellExecute = false;
				
			Process p = null;

			try {
				p = Process.Start (psi);
				p.WaitForExit ();
			} catch (Exception e) {
				Console.WriteLine ("Failed to execute iwtools scan: " + e.Message);
				yield break;
			}

			string line = null;

			while ((line = p.StandardOutput.ReadLine ()) != null) {
				line = line.Trim ();
			
				// Find the beginning of the record
				if (String.IsNullOrEmpty (line) || !line.StartsWith ("Cell"))
					continue;
			
				// Parse the MAC address
				string mac = line.Substring (line.IndexOf ("Address:") + 9);

				Network network = new Network (mac);

				while ((line = p.StandardOutput.ReadLine ()) != null) {
					line = line.Trim ();
					
					if (line.StartsWith ("ESSID"))
						network.Essid = line.Substring (7, line.Length - 8);
					
					if (line.StartsWith ("Quality")) {
						line = line.Substring (8);
						network.Quality = Double.Parse (line.Substring (0, line.IndexOf ('/')));
					
						line = line.Substring (line.IndexOf ("Signal level") + 13);
						network.SignalLevel = Double.Parse (line.Substring (0, line.IndexOf (' ')));

						line = line.Substring (line.IndexOf ("Noise level") + 12);
						network.NoiseLevel = Double.Parse (line.Substring (0, line.IndexOf (' ')));
					}

					if (line.StartsWith ("Mode"))
						network.Mode = line.Substring (5, line.Length - 5);
					
					if (line.StartsWith ("Encryption key"))
						network.Secure = (line.Substring (15, line.Length - 15) == "on");
				}
				
				yield return network;
			}
		}

		/*public static void Main ()
		{
			IwList iwlist = new IwList ();
			
			Location location = new Location ("Home");

			foreach (Network network in iwlist.Scan ()) {
				Console.WriteLine ("Network: {0} ({1})", network.Essid, network.Mac);
				Console.WriteLine ("Quality: {0}", network.Quality);
				Console.WriteLine ("Signal: {0}", network.SignalLevel);
				Console.WriteLine ("Noise: {0}", network.NoiseLevel);
				Console.WriteLine ("Mode: {0}", network.Mode);
				Console.WriteLine ("Secure: {0}", network.Secure);
				
				location.Networks.Add (network);
			}
		}*/
	}
}
